﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThouShaltNotBrick.Models;
using System.Xml.Linq;
using System.IO;
using GMLogging;

namespace ThouShaltNotBrick.DataAccess
{
    public static class CampaignXmlReader
    {
        #region Methods
        public static CampaignData Read(string pCampaignFilePath)
        {
            CampaignData campaignData = null;
            FileStream stream = null;
            try
            {
                stream = new FileStream(pCampaignFilePath, FileMode.Open, FileAccess.Read);
                XDocument campaignXDocument = XDocument.Load(stream);
                campaignData = Parse(campaignXDocument);
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                throw;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }

            return campaignData;
        }

        public static CampaignData Parse(string pCampaignInputString)
        {
            try
            {
                XDocument campaignXDocument = XDocument.Parse(pCampaignInputString);
                return Parse(campaignXDocument);
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                throw;
            }
        }

        private static CampaignData Parse(XDocument pCampaignXDocument)
        {
            XElement campaignXElement = pCampaignXDocument.Element(CampaignXmlConstants.TAG_CAMPAIGN);
            XAttribute campaignNameXAttribute = campaignXElement.Attribute(CampaignXmlConstants.TAG_CAMPAIGN_ATTRIBUTE_NAME);
            string campaignName = campaignNameXAttribute.Value;

            List<XElement> levelXElements = campaignXElement.Elements(CampaignXmlConstants.TAG_LEVEL).ToList();
            List<string> levelList = new List<string>();
            foreach (XElement levelXElement in levelXElements)
            {
                XAttribute levelNameXAttribute = levelXElement.Attribute(CampaignXmlConstants.TAG_LEVEL_ATTRIBUTE_NAME);

                string levelName = levelNameXAttribute.Value;
                levelList.Add(levelName);
            }

            CampaignData campaign = new CampaignData(campaignName, levelList);
            return campaign;
        }
        #endregion
    }
}